package com.example.a17376080_dlz_finaltest;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;
import okhttp3.Call;
import okhttp3.Response;
import okhttp3.internal.framed.Header;
import utils.HttpUtil;
import utils.MyNetCall;


public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText editTextP, editSMS, editTextCT;
    private Button button,SMSBtn;
    private TextView enterText;
    private ImageView returnImage;
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    String ii= (String) msg.obj;
                    Integer sss=Integer.valueOf(ii);
                    if(sss>0){
                        Toast.makeText(getApplicationContext(),"账号存在",Toast.LENGTH_SHORT).show();
                    }else {
                       // finish();
                        Intent intent=new Intent(RegisterActivity.this,EnterActivity.class);
                        intent.putExtra("username",editTextP.getText().toString().trim());
                        intent.putExtra("confirm_password",editTextCT.getText().toString().trim());
                        startActivity(intent);
                    }
                    break;
            }
        }
    };

    private EventHandler eventHandler = new EventHandler() {
        public void afterEvent(int event, int result, Object data) {
            // afterEvent会在子线程被调用，因此如果后续有UI相关操作，需要将数据发送到UI线程
            Message msg = new Message();
            msg.arg1 = event;
            msg.arg2 = result;
            msg.obj = data;
            new Handler(Looper.getMainLooper(), new Handler.Callback() {
                @Override
                public boolean handleMessage(Message msg) {
                    int event = msg.arg1;
                    int result = msg.arg2;
                    Object data = msg.obj;
                    if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理成功得到验证码的结果
                            // 请注意，此时只是完成了发送验证码的请求，验证码短信还需要几秒钟之后才送达
                        } else {
                            // TODO 处理错误的结果
                            ((Throwable) data).printStackTrace();
                        }
                    } else if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                        if (result == SMSSDK.RESULT_COMPLETE) {
                            // TODO 处理验证码验证通过的结果
                            //保存数据
                            register();
                        } else {
                            // TODO 处理错误的结果
                            Toast.makeText(RegisterActivity.this,"验证码错误！",Toast.LENGTH_SHORT).show();
                            ((Throwable) data).printStackTrace();
                        }
                    }
                    // TODO 其他接口的返回结果也类似，根据event判断当前数据属于哪个接口
                    return false;
                }
            }).sendMessage(msg);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_register_activity);
        // 注册一个事件回调，用于处理SMSSDK接口请求的结果
        SMSSDK.registerEventHandler(eventHandler);
        init();

    }

    private void init() {
        editTextP = (EditText) findViewById(R.id.et_phone_num);
        editSMS = (EditText) findViewById(R.id.et_sms_code);
        editTextCT = (EditText) findViewById(R.id.et_password);
        button = (Button) findViewById(R.id.bn_immediateRegistration);
        button.setOnClickListener(this);
        enterText = (TextView) findViewById(R.id.tv_enter);
        enterText.setOnClickListener(this);
        returnImage = (ImageView) findViewById(R.id.iv_return);
        returnImage.setOnClickListener(this);
        SMSBtn = (Button) findViewById(R.id.bn_sms_code);
        SMSBtn.setOnClickListener(this);
        final String username;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bn_immediateRegistration:
                SMSSDK.submitVerificationCode("86", editTextP.getText().toString().trim(), editSMS.getText().toString().trim());
                break;
            case R.id.tv_enter:
                returnEnter();
                break;
            case R.id.iv_return:
                returnEnter();
                break;
            case R.id.bn_sms_code:
                SMSSDK.getVerificationCode("86", editTextP.getText().toString().trim());
              //  SMSSDK.submitVerificationCode("86", editTextP.getText().toString().trim(), editSMS.getText().toString().trim());
                final String username = editTextP.getText().toString().trim();
                if (TextUtils.isEmpty(username)){
                    Toast.makeText(this, getResources().getString(R.string.User_name_cannot_be_empty), Toast.LENGTH_SHORT).show();
                    editTextP.requestFocus();
                }else {
                    Toast.makeText(this, "验证码获取成功", Toast.LENGTH_SHORT).show();
                }
                break;
        }
    }

    private void returnEnter() {
        Intent intent = new Intent(this,EnterActivity.class);
        startActivity(intent);
        finish();
    }

    public void register() {
        final String username = editTextP.getText().toString().trim();
        final String password = editSMS.getText().toString().trim();
        final String confirm_password = editTextCT.getText().toString().trim();
        if (TextUtils.isEmpty(username)) {  //当手机号没有输入时
            Toast.makeText(this, "手机号不能为空！", Toast.LENGTH_SHORT).show();
            editTextP.requestFocus();//使输入框失去焦点
            return;
        } else if (TextUtils.isEmpty(password)) {//当验证码没有输入时
            Toast.makeText(this, "验证码不能为空！", Toast.LENGTH_SHORT).show();
            editSMS.requestFocus();//使输入框失去焦点
            return;
        } else if (TextUtils.isEmpty(confirm_password)) {//当注册密码没有输入时
            Toast.makeText(this, "密码不能为空！", Toast.LENGTH_SHORT).show();
            editTextCT.requestFocus();//使输入框失去焦点
            return;
        }
        if (!TextUtils.isEmpty(username) && !TextUtils.isEmpty(password)) {
            final ProgressDialog pd = new ProgressDialog(this);
            pd.setMessage("正在注册……");
            pd.show();
            //okHttp请求
            String url = "http://106.14.221.71:8080/Service_dlz//user_saveUser.action";
            Map map=new HashMap();
            map.put("phone",username);
            map.put("password",confirm_password);
            HttpUtil.postDataAsyn(url, map, new MyNetCall() {
                @Override
                public void success(Call call, Response response) throws IOException {
                    Log.d("账号密码提交成功", username+"---"+confirm_password);
                   pd.dismiss();
                  // finish();
                   String ttt=response.body().string();
                   ttt=ttt.trim();
                    Message message=new Message();
                    message.obj=ttt;
                    message.what=1;
                    handler.sendMessage(message);

               }

                @Override
                public void failed(Call call, IOException e) {
                    Log.d("账号密码提交失败", "failed: ");
                }
            });
//            new Thread(new Runnable() {
//                public void run() {
//                    //注册的操作放在此处
//                    try {
//                        Thread.sleep(2000);
//                        Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
//                    } catch (InterruptedException e) {
//
//                    }
//                    pd.dismiss();
//                  //  Toast.makeText(RegisterActivity.this, "注册成功", Toast.LENGTH_SHORT).show();
//                }
//            }).start();

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterEventHandler(eventHandler);
    }
}